<?php

namespace App\Http\Controllers;

use App\Http\Requests\StatisticRequest;
use App\Models\Cashflow;
use FFI;
use Iamxcd\LaravelCRUD\Traits\HasResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

/**
 * 统计
 */
class StatisticController extends Controller
{
    use HasResponse;
    public function __construct()
    {
        $this->request = app(StatisticRequest::class);
    }


    public function  statisticByType()
    {
        /**
         * type year month statisticTypeData
         * year
         * month
         */

        $params = $this->request->validated();
        $user = Auth::user();
        if (isset($params['cashbook_id']) && !is_null($params['cashbook_id'])) {
            Cashflow::cashbookCheck($user->id, $params['cashbook_id']);
            $cashbook_id = $params['cashbook_id'];
        } else {
            $cashbook_id = $user->default_cashbook_id;
        }

        $res = DB::table('cashflows as cf')
            ->selectRaw('sum(cf.amount) as value, cg.name as name')
            ->leftJoin('categories as cg', 'cg.id', '=', 'cf.category_id')
            ->where('cf.user_id', $user->id)
            ->where('cf.cashbook_id', $cashbook_id)
            ->where('cf.year', $params['year'])
            ->where('cf.type', $params['type'])
            ->when($params['query_type'] == 'month', function ($query) use ($params) {
                $query->where('cf.month', $params['month']);
            })
            ->groupBy('cf.category_id')
            ->get()
            ->toArray();
        foreach ($res as &$item) {
            $item->value =  round($item->value, 2);
        }

        return $this->response($res, '获取成功');
    }
}
